package com.zlm.app;

import com.zlm.bean.ChannelPromotionCount;
import com.zlm.bean.MarketingUserBehavior;
import com.zlm.common.SimulateMarketingBehaviorSourceFunction;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;


/**
 * Author: Harbour
 * Date: 2021-05-16 23:07
 * Desc: 分析市场用户行为的app
 */
public class MarketChannelApp {
    public static void main(String[] args) throws Exception {

        // step 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // step 2 获取数据源
        DataStream<MarketingUserBehavior> inputDataStream = env.addSource(new SimulateMarketingBehaviorSourceFunction());

        // step 3 对数据源进行转换
        inputDataStream
                .assignTimestampsAndWatermarks(new AscendingTimestampExtractor<MarketingUserBehavior>() {
                    @Override
                    public long extractAscendingTimestamp(MarketingUserBehavior element) {
                        return element.getTimestamp();
                    }
                })
                .keyBy("channel", "behavior")
                .timeWindow(Time.hours(1), Time.seconds(5))
                .aggregate(new MyAggFunction(), new MyWindowFunction())
                .print();

        env.execute();
    }

    private static class MyWindowFunction extends ProcessWindowFunction<Long, ChannelPromotionCount, Tuple, TimeWindow> {

        @Override
        public void process(Tuple tuple, Context context, Iterable<Long> elements, Collector<ChannelPromotionCount> out) throws Exception {
            ChannelPromotionCount channelPromotionCount = new ChannelPromotionCount(
                    tuple.getField(0),
                    tuple.getField(1),
                    new Timestamp(context.window().getEnd()).toString(),
                    elements.iterator().next()
            );
            out.collect(channelPromotionCount);
        }
    }

    private static class MyAggFunction implements AggregateFunction<MarketingUserBehavior, Long, Long> {
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(MarketingUserBehavior value, Long accumulator) {
            return accumulator + 1;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return a + b;
        }
    }

}
